<template>
	<view class="content" style="overflow: hidden;">
		<u-navbar
			title="详情" 
			:bg-color="`${mainColor}`" 
			fixed 
			placeholder 
			autoBack
			:height="navigationBarHeight"
			:title-style="{color:`${textColor}`, fontSize:'16px', fontWeight:700}"
			:left-icon-color="`${textColor}`"
			v-if="showTitle"
			/>
		<view style="background-color: #fff;">
			<u-tabs
				:lineColor="`${mainColor}`"
				lineWidth="46px"
				:current="index"
				@change="({index}) => selection = tabs[index]"
				:list="tabs"></u-tabs>
		</view>
		<scroll-view scroll-y :style="{maxHeight: `calc(100vh - 104px - ${navHeight}px)`}">
			<view class="content-page">
				<view class="main-box">
					<view class="input-item flex-b" @click="showCardTypes=true">
						<view class="flex-a">
							<view class="text1">
								{{onlineAudit ? '种类' : '卡种'}}
							</view>
							<view class="text2" v-if="card.name">
								<image :src="baseUrl(card.icon)" class="card-img"></image>
								{{card.name}}
							</view>
						</view>
						<u-icon name="arrow-right" size="16" color="#606266"></u-icon>
					</view>
					<view class="input-item flex-b" @click="clickFaceValue()">
						<view class="flex-a">
							<view class="text1">
								{{onlineAudit ? '价格' : '面值'}}
							</view>
							<view class="text2" v-if="faceValue.price">
								￥{{faceValue.price}}
							</view>
							<view class="text2" v-else style="color: #999;">
								请选择
							</view>
						</view>
						<u-icon name="arrow-right" size="16" color="#606266"></u-icon>
					</view>
					<view class="input-item flex-b" v-if="!onlineAudit">
						<view class="flex-a">
							<view class="text1">
								价格
							</view>
							<view class="text2" v-if="faceValue.recycling_price">
								￥{{faceValue.recycling_price}}
							</view>
							<view class="item-zk" v-if="faceValue.discount">{{faceValue.discount.toFixed(1)}}折
							</view>
						</view>
					</view>
				</view>
				<view class="tip-text" v-if="faceValue.price && detail.notice">{{detail.notice}}</view>
				<view class="submit-box" v-if="faceValue.price && !onlineAudit">
					<view class="tab-bar flex-ar">
						<view :class="{active: item.id === selectSubmitTab.id}" @click="switchSubmitTab(item)" v-for="(item, index) in submitTabs" :key="index">
							{{item.label}}
							<view class="line"></view>
						</view>
					</view>
					<view v-if="selectSubmitTab.label == '单卡提交'">
						<view class="input-class flex-a" v-if="detail.need_card_no">
							卡号
							<input :value="cardNumber" class="input-c" @input="cardNumberChanged" style="flex: 1 1 0%;" placeholder="请输入充值卡卡号"/>
						</view>
						<view class="input-class flex-a">
							卡密
							<input :value="cardPassword" class="input-c" @input="cardPasswordChanged" style="flex: 1 1 0%;" placeholder="请输入充值卡卡密"/>
						</view>
					</view>
					<view v-if="selectSubmitTab.label == '批量提交'" class="text7">
						<textarea :value="cardsText" @input="cardsTextChanged" :maxlength="-1" :cols="300" :rows="100" style="width: 100%;" 
							:placeholder="detail.need_card_no ? '每张卡占用一行,卡号与密码之间用\'空格\'隔开' : '每张卡占用一行，只需输入卡密'"></textarea>
					</view>
				</view>
				<view class="flex-b arrange-card" v-if="faceValue.price && selectSubmitTab.label == '批量提交'">
					<view>
						<u-button :color="`${mainColor}`" :custom-style="{width: '72px', height:'31px', padding:'4px', color: `${textColor}`}"
							@click="arrangeCards">整理卡密</u-button>
					</view>
					<view>
						已输入<text class="color1">{{cards.length}}</text>张<text class="color1">{{faceValue.price}}</text>元面值的卡，最多<text class="color1">100</text>张
					</view>
				</view>
				<view class="tip-text" v-if="faceValue.price && !onlineAudit && detail.remark">
					{{detail.remark}}
				</view>
				<view class="tip-box">
					<view class="text4 flex-a">
						<view class="line-y">
						</view>
						<view class="title">
							{{onlineAudit ? '说明' : '兑换说明'}}
						</view>
					</view>
					<view class="tip-content">
						<rich-text :nodes="intro"></rich-text>
					</view>
				</view>
			</view>
		</scroll-view>	
		<u-popup :show="showCardTypes" @close="showCardTypes=false" closeable>
			<view class="tan-box">
				<view class="title">
					选择{{onlineAudit ? '种类' : '卡种'}}
				</view>
				<scroll-view scroll-y style="height: 76vh;">
					<view class="card-item" v-for="(item, index) in selection.cards" :key="index"
							@click="selectCard(item)">
						<view class="title2 flex-a">
							<image :src="baseUrl(item.icon)" class="card-img"></image>{{item.name}}
						</view>
						<u-icon name="checkbox-mark" color="success" size="20" v-if="item.id === card.id"></u-icon>
					</view>
					<view class="card-item" style="border-bottom: none;"></view>
				</scroll-view>
			</view>
		</u-popup>
		<u-popup :show="showFaceValueList" @close="showFaceValueList=false" closeable>
			<view class="tan-box">
				<view class="title">
					{{onlineAudit ? '选择价格' : '选择面值'}}
				</view>
				<view class="text5">
					<image :src="baseUrl(card.icon)" class="card-img">{{card.name}}
				</view>
				<view class="tips">
					{{onlineAudit ? '价格' : '面值'}}选错将无法结算！
				</view>
				<scroll-view scroll-y style="max-height: 60vh; overflow-y: auto;">
					<view class="list-box flex-a">
						<view class="item" v-for="(item, index) in faceValueList" :key="index" 
							@click="selectFaceValue(item)">
							<view class="item-index">
								<view class="cost-price">
									￥{{item.price}}
								</view>
								<view class="price">
									价格:
									<text class="text6">{{item.recycling_price}}</text>
									<text class="zhekou">{{item.discount.toFixed(1)}}折</text>
								</view>
							</view>
						</view>
						<view class="item" v-if="detail.is_support_custom"
							@click="clickCustomFaceValue">
							<view class="item-index">
								自定义{{onlineAudit ? '价格' : '面值'}}
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<u-popup :show="showConfirm && !onlineAudit" @close="showConfirm=false" closeable>
			<view class="tan-box" style="padding-bottom: 80px;">
				<view class="title">
					请确认一下协议再提交
				</view>
				<view class="agreement flex-a">
					<u-checkbox-group v-model="check1" @change="(v) => checkChanged(0, v)">
						<u-checkbox name="check1" shape="circle" :active-color="`${mainColor}`"></u-checkbox>
					</u-checkbox-group>
					<view>
						<text>我已阅读、理解并接受</text>
						<text class="text8">《卡券转让协议》</text>
					</view>
				</view>
				<view class="agreement flex-a">
					<u-checkbox-group v-model="check2" @change="(v) => checkChanged(1, v)">
						<u-checkbox name="check2" shape="circle" :active-color="`${mainColor}`"></u-checkbox>
					</u-checkbox-group>
					<view>
						<text>我已确认该卡号卡密</text>
						<text class="text8">来源合法，如有问题，本人愿意承担一切法律责任</text>
					</view>
				</view>
				<view class="btn-box">
					<view class="submit-btn">
						<u-button shape="circle" :color="`${mainColor}`" @click="doSubmit"
							:custom-style="{color: `${textColor}`}">确认提交</u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup :show="showCustomFaceValue" mode="center">
			<u-modal show :title="onlineAudit ? '自定义价格' : '自定义面值'" showCancelButton
				@cancel="showCustomFaceValue=false" @confirm="setCustomFaceValue">
				<view class="slot-content">
					<view class="flex-b" style="align-items: center; gap: 8px;">
						<view class="label">{{onlineAudit ? '价格' : '卡券面值'}}</view>
						<input type="digit" :value="customFaceValue" @input="customFaceValueChanged" 
							:placeholder="onlineAudit ? '请输入价格' : '请输入卡券面值'" class="input-class u-border" auto-focus/>
					</view>
					<view class="tips">
						自定义{{onlineAudit ? '价格' : '面值'}}范围：{{detail.min_custom_face_value}}~{{detail.max_custom_face_value}}元
					</view>
				</view>
			</u-modal>
		</u-popup>
		
		<view class="fix-bottm flex-b">
			<view class="left-btn" v-if="!onlineAudit">
				<u-button plain hairline :color="`${mainColor}`" @click="clickKefu">联系客服</u-button>
			</view>
			<view class="right-btn" :style="onlineAudit ? 'width: 100%' : ''">
				<u-button :color="`${mainColor}`" @click="clickExchange"
					:custom-style="{color: `${textColor}`}">立即回收</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import token from '@/utils/token';
	import { systemInfo } from '@/utils/mixin';
	import { baseUrl, exchangeCard, exchangeCards, getCategories, getDetail } from '@/api';
	import { customerService } from '@/utils/service';
	import {mapState, mapGetters} from "vuex";

	export default {
		mixins: [systemInfo],
		data() {
			return {
				baseUrl,
				cardId: null,
				index: 0,
				selection: {},
				tabs: [],
				card: {},
				detail: {},
				faceValue: {},
				faceValueList: [],
				submitTabs: [{
					id: 1,
					label: '单卡提交',
				},
				{
					id: 2,
					label: '批量提交'
				}
				],
				selectSubmitTab: {},
				cardNumber: '',
				cardPassword: '',
				cardsText: '',
				cards: [],
				showCardTypes: false,
				showFaceValueList: false,
				showConfirm: false,
				showCustomFaceValue: false,
				customFaceValue: '',
				check1: [],
				check2: [],
				check: [],
				intro: ""
			}
		},
		computed: mapState([
			'onlineAudit'
		]),
		async onLoad({categoryId, cardId}) {
			this.cardId = cardId;
			this.getSystemInfo();
			const res = await getCategories();
			this.tabs = res.data;
			if (this.tabs.length > 0) {
				if (categoryId) {
					const index = this.tabs.findIndex((item) => item.id == categoryId);
					this.index = index >= 0 ? index : 0;
				} else if (cardId) {
					const index = this.tabs.findIndex((item) => item.cards.findIndex((card) => card.id == cardId) >= 0);
					this.index = index >= 0 ? index : 0;
				}
				this.selection = this.tabs[this.index];
			}
		},
		methods: {
			selectCard(item) {
				this.card = item;
				this.showCardTypes = false;
				this.showFaceValueList = true;
			},
			clickFaceValue() {
				if (token.check()) return;
				
				this.showFaceValueList = true;
			},
			selectFaceValue(item) {
				if (token.check()) return;
				
				this.faceValue = item;
				this.showFaceValueList = false;
				this.selectSubmitTab = this.submitTabs[0];
				this.cardNumber = '';
				this.cardPassword = '';
				this.cardsText = '';
				this.cards = [];
			},
			switchSubmitTab(item) {
				this.selectSubmitTab = item;
			},
			cardNumberChanged({detail}) {
				this.cardNumber = detail.value.trim();
			},
			cardPasswordChanged({detail}) {
				this.cardPassword = detail.value.trim();
			},
			cardsTextChanged({detail}) {
				this.cardsText = detail.value.trim();
			},
			clickCustomFaceValue() {
				if (this.detail.custom_discounts.length == 0) {
					this.notify('自定义卡券面值维护中！');
					return;
				}
				
				this.showCustomFaceValue = true;
			},
			customFaceValueChanged({detail}) {
				this.customFaceValue = detail.value.trim();
			},
			setCustomFaceValue() {
				if (this.customFaceValue.length == 0) {
					this.notify('请输入您的卡券面值！');
					return
				}
				const faceValue = parseFloat(this.customFaceValue);
				if (faceValue < this.detail.min_custom_face_value) {
					this.notify(`卡券面值必须大于${this.detail.min_custom_face_value}元`);
					return
				}
				
				if (faceValue > this.detail.max_custom_face_value) {
					this.notify(`卡券面值必须小于${this.detail.max_custom_face_value}元`);
					return
				}
				
				const customDiscount = this.getCustomDiscount(faceValue);
				if (!customDiscount) {
					this.notify('卡券面值不存在或已下架！')
				}
				
				const recycelingPrice = faceValue * customDiscount.discount / 100;
				
				this.selectFaceValue({
					price: faceValue.toFixed(2),
					recycling_price: recycelingPrice.toFixed(2)
				});
				this.showCustomFaceValue = false;
			},
			getCustomDiscount(faceValue) {
				return this.detail.custom_discounts.find((item) => faceValue >= item.min_face_value && faceValue <= item.max_face_value);
			},
			arrangeCards() {
				const lines = this.cardsText.replace(/[^\S\r\n]+/g, ' ').split('\n');
				const cards = [];
				const cached = new Set();
				let cardsText = '';
				for (let line of lines) {
					line = line.trim()
					if (this.detail.need_card_no) {
						const index = line.indexOf(' ');
						if (index >= 0) {
							const card_no = line.substring(0, index+1).trim();
							const card_pw = line.substring(index).trim().split(' ')[0]
							const card = `${card_no} ${card_pw}`
							if (!cached.has(card)) {
								cardsText += card;
								cardsText += '\n';
								cards.push({
									card_no,
									card_pw
								});
								cached.add(card);
							}
						}
					} else {
						const card = line.split(' ')[0]
						if (!cached.has(card)) {
							cardsText += card;
							cardsText += '\n';
							cards.push({
								card_no: null,
								card_pw: card
							});
							cached.add(card);
						}
					}
				}
				this.cardsText = cardsText;
				this.cards = cards;
			},
			clickKefu() {
				customerService.openChat();
			},
			clickExchange() {	
				if (!this.faceValue.price) {
					this.notify(this.onlineAudit ? '请先选择价格！' : '请先选择面值！');
					return
				}
				
				if (this.onlineAudit) {
					if (token.check()) {
						this.setToast('请先登录后再提交~');
						return;
					}
					
					this.setToast('提交成功，请等待后续处理~');
					uni.switchTab({
						url:'/pages/index/index'
					});
					return
				}
				
				if (this.selectSubmitTab.id == 1) {
					if (this.detail.need_card_no && this.cardNumber.length === 0) {
						this.notify('卡号不能为空！');
						return
					}
					if (this.cardPassword.length === 0) {
						this.notify('卡密不能为空');
						return
					}
				} else if (this.selectSubmitTab.id == 2) {
					this.arrangeCards();
					if (this.cards.length <= 0) {
						this.notify('请输入您的卡券');
						return
					}
					if (this.cards.length > 100) {
						this.notify('一次最多只能兑换100张！');
						return
					}
				} else {
					return
				}
				
				this.check1 = [];
				this.check2 = [];
				this.check = [];
				this.showConfirm = true;
			},
			checkChanged(index, value) {
				this.check[index] = value.length > 0;
			},
			async doSubmit() {
				if (this.check.filter((item) => item == true).length < 2) {
					this.notify('您必须同意所有协议！');
					return
				}
				
				if (this.selectSubmitTab.id == 1) {
					const res = await exchangeCard(this.detail.id, this.faceValue.id,
						this.faceValue.price, this.cardNumber, this.cardPassword);
					if (res.code === 2000) {
						this.setToast(res.msg);
						uni.navigateTo({
							url:'/pages/order/index'
						});
					}
				} else if (this.selectSubmitTab.id == 2) {
					const res = await exchangeCards(this.detail.id, this.faceValue.id,
						this.faceValue.price, this.cards);
					if (res.code === 2000) {
						this.setToast(res.msg);
						uni.navigateTo({
							url:'/pages/order/index'
						});
					}
				}
				this.check1 = [];
				this.check2 = [];
				this.check3 = [];
				this.check = [];
				this.cardNumber = '';
				this.cardPassword = '';
				this.cardsText = '';
				this.cards = [];
				this.showConfirm = false;
			},
			notify(message) {
				uni.showToast({
					icon:'none',
					title:message
				})
			}
		},
		watch: {
			selection: async function(value, oldValue) {
				if (value.id !== oldValue.id) {
					if (value.cards.length > 0) {
						if (this.cardId) {
							this.card = value.cards.find((item) => item.id == this.cardId);
							this.cardId = null;
							this.showFaceValueList = true;
							if (!this.card) {
								this.card = value.cards[0];
							}
						} else {
							this.card = value.cards[0];
						}
					}
				}
			},
			card: async function(value, oldValue) {
				if (value.id !== oldValue.id) {
					const res = await getDetail(value.id);
					const detail = res.data.detail;
					this.faceValue = {}
					this.detail = detail;
					this.faceValueList = detail.face_values;
					this.intro = res.data.intro.replaceAll('\n', '<br>')
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.content-page {
    padding: 0px 10px 16px;
    box-sizing: border-box;
	
	.main-box {
	    box-shadow: 0 0 5px 0 rgba(0, 0, 0, .1);
	    border-radius: 8px;
		margin-top: 16px;
		
		.input-item {
		    font-family: Times New Roman;
		    height: 52px;
		    line-height: 52px;
		    padding: 5px 10px;
		    box-sizing: border-box;
		    border-bottom: 1px solid #f1f1f1;
		    position: relative;
			display: flex;
			align-items: center;
			
			.text1 {
			    color: #666;
			    margin-right: 5px;
			    width: 62px;
			}
			
			.text2 {
				display: flex;
				align-items: center;
				
				.card-img {
					width: 20px;
					height: 20px;
					margin-right: 8px;
					box-sizing: border-box;
					border-radius: 50%;
				}
			}
			
			.item-zk {
			    background-color: #fff5f4;
			    position: absolute;
			    right: 10px;
			    top: 15px;
			    font-size: 14px;
			    height: 20px;
			    line-height: 20px;
			    padding: 0 10px;
			    color: #e33233;
			    border-radius: 8px;
			}
		}
	}
	
	.tip-box {
		.text4 {
		    margin: 20px 0 10px;
			
			.line-y {
			    position: relative;
			    top: 3px;
			    margin-right: 10px;
			    width: 4px;
			    height: 15px;
			    background-color: $main-color;
			}
		}
		
		.tip-content {
		    font-size: 12px;
		    padding-left: 15px;
		    line-height: 19px;
		    color: #333;
		}
	}
}

.tip-text {
    font-family: Times New Roman;
    padding: 5px 10px;
    font-size: 14px;
    background-color: #fff5f4;
    margin-top: 10px;
}

.submit-box {
    margin-top: 10px;
    box-shadow: 0 1px 20px 0 hsla(0, 0%, 76.5%, .38);
	
	.tab-bar {
	    padding-top: 0.5px;
	    height: 41px;
	    line-height: 41px;
	    border-bottom: 1px solid #f1f1f1;
	    background-color: #fff;
		
		.active {
		    position: relative;
		    font-weight: 500;
		    color: $main-color;
			
			.line {
			    position: absolute;
			    width: 100%;
			    height: 3px;
			    bottom: 0px;
			    left: 0;
			    background-color: $main-color;
			}
		}
	}
	
	.input-class {
	    position: relative;
	    font-size: 14px;
	    border-top: 0.5px solid #f1f1f1;
	    background-color: #fff;
	    height: 52px;
	    line-height: 52px;
	    padding: 0 20px;
		
		.input-c {
		    margin-top: 15px;
		    margin-left: 15px;
		}
		
		.scan-img {
		    width: 31px;
		    height: 31px;
		    position: absolute;
		    top: 10px;
		    right: 20px;
		}
	}
	
	.text7 {
	    padding: 10px;
	    box-sizing: border-box;
	}
}

.arrange-card {
    margin-top: 10px;
    font-size: 13px;
	
	.color1 {
	    line-height: 31px;
	    color: #f65e5e;
	}
}

.slot-content {
	margin-top: 20px;
	
	.label {
		font-size: 14px;
		color: #666;
	}
	
	.input-class {
		padding: 6px 9px;
		border-radius: 4px;
		font-size: 14px;
	}
	
	.tips {
	    font-size: 14px;
	    width: 100%;
	    height: 31px;
	    line-height: 31px;
	    text-align: center;
	    color: #e33233;
	    background-color: #fff5f4;
	    margin-top: 16px;
	}
}

.fix-bottm {
    position: fixed;
    bottom: 0;
    left: 0;
	right: 0;
    padding: 10px;
    z-index: 1;
    box-sizing: border-box;
    background-color: #fff;
	
	.left-btn {
	    position: relative;
	    width: 30%;
	}
	
	.right-btn {
	    width: 65%;
	}
}
.tan-box {
    width: 100%;
    padding: 15px;
    box-sizing: border-box;
	
	.title {
	    height: 31px;
	    line-height: 31px;
	    padding-bottom: 10px;
	    border-bottom: 1px solid #f1f1f1;
	}
	
	.card-item {
		height: 31px;
		line-height: 31px;
		padding: 10px 0;
		border-bottom: 1px solid #f1f1f1;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		
		.title2 {
			.card-img {
			    position: relative;
			    top: 2px;
			    width: 26px;
			    height: 26px;
			    margin-left: 15px;
			    margin-right: 10px;
			    box-sizing: border-box;
			}
		}
	}
	
	.text5 {
	    font-size: 14px;
	    color: #666;
	    margin: 10px 0;
		display: flex;
		align-items: center;
		
		.card-img {
			width: 18px;
			height: 18px;
			margin-right: 4px;
			box-sizing: border-box;
			border-radius: 50%;
		}
	}
	
	.tips {
	    font-size: 14px;
	    width: 100%;
	    height: 31px;
	    line-height: 31px;
	    text-align: center;
	    color: #e33233;
	    background-color: #fff5f4;
	    margin-bottom: 10px;
	}
	
	.list-box {
	    flex-wrap: wrap;
		
		.item {
		    position: relative;
		    text-align: center;
		    padding-top: 10px;
		    width: 32%;
		    margin-bottom: 10px;
		    box-sizing: border-box;
		    background-color: #ececec;
		    font-size: 14px;
		    font-family: Times New Roman;
		    margin-right: 2%;
			
			.item-index {
			    position: relative;
			    z-index: 9;
				
				.cost-price {
				    margin-bottom: 5px;
				    font-size: 13px;
				    font-weight: bold;
				}
				
				.price {
				    font-size: 11px;
				    margin-bottom: 10px;
					
					.text6 {
					    margin-left: 3px;
					    font-size: 11px;
					}
					
					.zhekou {
					    border-radius: 2px;
					    margin-left: 4px;
					    color: #e33233;
					    padding: 0 5px;
					    border-radius: 4px;
					}
				}
			}
		}
		
		.item:active {
			background-color: rgba(236,236,236,0.8);
		}
		
		.item:nth-child(3n) {
		    margin-right: 0;
		}
	}
	
	.agreement {
	    position: relative;
	    padding: 10px 0;
	    color: #666;
	    font-size: 14px;
	    border-bottom: 1px solid #f1f1f1;
		
		.text8 {
		    color: #e33233;
		}
	}
	
	.btn-box {
		position: absolute;
		bottom: 20px;
		left: 20px;
		right: 20px;
		
		.submit-btn {
		    height: 39px;
		    line-height: 39px;
		    color: #fff;
		    font-size: 15px;
		    font-weight: 500;
		    text-align: center;
		}
	}
}
</style>
